﻿using log4net;
using System;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 会员设置界面 : Form
    {
        private readonly IMemberInfoRepository MemberInfoReposioty = new MemberInfoRepository();
        private readonly IMoneyFlowRepository MoneyFlowReposioty = new MoneyFlowRepostitory();

        //错误日志
        private readonly ILog logger = LogManager.GetLogger(typeof(会员设置界面));

        //操作日志
        private readonly ISysLogRepository LogReposioty = new SysLogRepository();

        private readonly string UserId = "";

        #region 窗体绘制

        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #endregion 窗体绘制

        public 会员设置界面(string userid)
        {
            this.UserId = userid;
            InitializeComponent();
        }

        private void 会员设置界面_Load(object sender, EventArgs e)
        {
            comSex.SelectedIndex = 1;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            BindData();
        }

        public void BindData()
        {
            string seacher = txtUserName.Text.Trim();

            StringBuilder where = new StringBuilder(" where 1=1 ");
            StringBuilder where1 = new StringBuilder(" where 1=1 ");
            StringBuilder where2 = new StringBuilder(" 1=1 ");
            string beginDate = dtpStart.Text;
            string endDate = dtpEnd.Text;
            if (!beginDate.IsNullOrEmpty())
            {
                where.Append($" and CONVERT(VARCHAR,CreateTime,23) >= '{DateTime.Parse(beginDate).ToString("yyyy-MM-dd")}'");
                where1.Append($" and CONVERT(VARCHAR,CreateTime,23) >= '{DateTime.Parse(beginDate).ToString("yyyy-MM-dd")}'");
                where2.Append($" and CONVERT(VARCHAR,CreateTime,23) >= '{DateTime.Parse(beginDate).ToString("yyyy-MM-dd")}'");
            }
            if (!endDate.IsNullOrEmpty())
            {
                where.Append($" and CONVERT(VARCHAR,CreateTime,23) <= '{DateTime.Parse(endDate).ToString("yyyy-MM-dd")}'");
                where1.Append($" and CONVERT(VARCHAR,CreateTime,23) <= '{DateTime.Parse(endDate).ToString("yyyy-MM-dd")}'");
                where2.Append($" and CONVERT(VARCHAR,CreateTime,23) <= '{DateTime.Parse(endDate).ToString("yyyy-MM-dd")}'");
            }
            //where.Append($" and [Type] like '%充值%' ");
            //where1.Append($" and [Type] not like '%充值%' ");
            var Chongzhilist01 = MoneyFlowReposioty.GetMoneyFlowList(where.ToString() + " and [Type] = '普通会员充值' "); //充值品鉴金额 普通会员充值

            var Chongzhilist02 = MoneyFlowReposioty.GetMoneyFlowList(where.ToString() + " and [Type] = '理疗充值' "); //充值理疗金额 理疗充值
            where2.Append($" and (Phone like '%{seacher}%'  or UserName like '%{seacher}%')  ");
            lblPinJian.Text = Chongzhilist01.ToString() + "￥";
            lblLiLiao.Text = Chongzhilist02.ToString() + "￥";

            var productList = MemberInfoReposioty.GetMemberInfoList(where2.ToString());
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = productList;
        }

        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            txtName.Text = "";
            txtPhone.Text = "";
            txtCard.Text = "";
            txtLLCard.Text = "";
            txtId.Text = "0";
            txtAccount.Text = "0.00";
            txtLLAccount.Text = "0.00";
            txtCreateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            this.tabControl1.SelectedIndex = 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MemberInfo m = new MemberInfo();
            if (string.IsNullOrEmpty(txtName.Text.Trim()) || string.IsNullOrEmpty(txtPhone.Text.Trim()) || (string.IsNullOrEmpty(txtCard.Text.Trim()) && string.IsNullOrEmpty(txtLLCard.Text.Trim())))
            {
                MessageBox.Show("请完善信息再保存!");
            }
            else
            {
                m.AccountMoney = 0;
                m.Birthdate = DateTime.Now;
                m.IdNumber = "";
                m.MemberCard = txtCard.Text.Trim();
                m.Phone = txtPhone.Text.Trim();
                m.UserName = txtName.Text.Trim();
                m.Sex = comSex.Text.ToString() == "男" ? true : false;
                m.AccountMoney = Convert.ToDecimal(txtAccount.Text.Trim());
                m.LLAccountMoney = Convert.ToDecimal(txtLLAccount.Text.Trim());
                m.LLCard = txtLLCard.Text.Trim();
                if (txtId.Text.Trim() != "0")
                {
                    string Id = dataGridView1.SelectedRows[0].Cells["会员编号"].Value.ToString();
                    MemberInfo p = MemberInfoReposioty.Get(Convert.ToInt32(Id));
                    m.CreateTime = p.CreateTime;
                    m.Id = p.Id;
                    //编辑
                    if (MemberInfoReposioty.Update(m) > 0)
                    {
                        LogReposioty.AddLog(Convert.ToInt32(UserId), "会员信息修改完成", m);
                        MessageBox.Show("修改成功!");
                        this.tabControl1.SelectedIndex = 0;
                        BindData();
                    }
                    else
                    {
                        MessageBox.Show("修改失败!");
                    }
                }
                else
                {
                    m.CreateTime = DateTime.Now;

                    //新增
                    if (MemberInfoReposioty.Insert(m) > 0)
                    {
                        LogReposioty.AddLog(Convert.ToInt32(UserId), "会员添加完成", m);
                        MessageBox.Show("添加成功!");
                        this.tabControl1.SelectedIndex = 0;
                        BindData();
                    }
                    else
                    {
                        MessageBox.Show("添加失败!");
                    }
                }
            }
        }

        private void toolStripDropDownButton4_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 0)
            {
                string Id = dataGridView1.SelectedRows[0].Cells["会员编号"].Value.ToString();
                string Tym = dataGridView1.SelectedRows[0].Cells["会员姓名"].Value.ToString();
                DialogResult RSS = MessageBox.Show(this, $"确定要删除会员{Tym}？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (RSS == DialogResult.Yes)
                {
                    int res = MemberInfoReposioty.Delete(int.Parse(Id));
                    if (res > 0)
                    {
                        string LogStr = $"删除{Tym}成功";
                        MessageBox.Show("删除成功");
                        LogReposioty.AddLog(Convert.ToInt32(UserId), LogStr);
                        BindData();
                    }
                }
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripDropDownButton3_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 0)
            {
                string Id = dataGridView1.SelectedRows[0].Cells["会员编号"].Value.ToString();
                MemberInfo m = MemberInfoReposioty.Get(Convert.ToInt32(Id));
                txtAccount.Text = m.AccountMoney.ToString();
                txtLLAccount.Text = m.LLAccountMoney.ToString();
                txtCard.Text = m.MemberCard;
                txtLLCard.Text = m.LLCard;
                txtName.Text = m.UserName;
                txtPhone.Text = m.Phone;
                txtId.Text = m.Id.ToString();
                comSex.SelectedItem = m.Sex == true ? "男" : "女";
                txtCreateTime.Text = m.CreateTime.ToString();
                this.tabControl1.SelectedIndex = 1;
            }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string Id = dataGridView1.SelectedRows[0].Cells["会员编号"].Value.ToString();
                MemberInfo m = MemberInfoReposioty.Get(Convert.ToInt32(Id));
                txtAccount.Text = m.AccountMoney.ToString();
                txtLLAccount.Text = m.LLAccountMoney.ToString();
                txtCard.Text = m.MemberCard;
                txtLLCard.Text = m.LLCard;
                txtName.Text = m.UserName;
                txtPhone.Text = m.Phone;
                txtId.Text = m.Id.ToString();
                comSex.SelectedItem = m.Sex == true ? "男" : "女";
                txtCreateTime.Text = m.CreateTime.ToString();
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选择药品!");
            }
        }

        private void toolStripDropDownButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
           e.RowBounds.Location.Y,
           dataGridView1.RowHeadersWidth - 4,
           e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            Users_count.Text = "会员总数：" + (dataGridView1.Rows.Count).ToString() + " ";
        }

        /// <summary>
        /// 会员充值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVip_Click(object sender, EventArgs e)
        {
            //会员id
            int id = Convert.ToInt32(txtId.Text.Trim());
            //卡号
            string Card = txtCard.Text.Trim();
            if (string.IsNullOrEmpty(Card))
            {
                MessageBox.Show("请检查会员卡号是否正确");
            }
            else
            {
                //充值
                会员充值 frmNum = new Forms.会员充值(Card, id, 0, Convert.ToInt32(this.UserId));
                frmNum.ShowDialog();
            }
        }

        /// <summary>
        /// 理疗充值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLL_Click(object sender, EventArgs e)
        {
            //会员id
            int id = Convert.ToInt32(txtId.Text.Trim());
            //卡号
            string Card = txtLLCard.Text.Trim();
            if (string.IsNullOrEmpty(Card))
            {
                MessageBox.Show("请检查理疗卡号是否正确");
            }
            else
            {
                //充值
                会员充值 frmNum = new Forms.会员充值(Card, id, 1, Convert.ToInt32(this.UserId));
                frmNum.ShowDialog();

            }
        }

        private void toolStripDropDownButton2_Click_1(object sender, EventArgs e)
        {
            BindData();
            this.tabControl1.SelectedIndex = 0;

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            BindData();
        }
    }
}